<template>
 <div class="category">
   <!-- 左侧一级菜单渲染 -->
   <van-sidebar v-model="active" @change="handleCateChange">
      <van-sidebar-item 
         v-for="category in categorys"
         :key="category.id"
         :title="category.name" 
      />
      <!-- <van-sidebar-item title="标签名称" />
      <van-sidebar-item title="标签名称" /> -->
   </van-sidebar>
   <!-- 右侧宫格渲染 -->
    <div class="right">
      <van-grid :border="false">
         <van-grid-item
            v-for="item in subCategorys"
            :key="item.id"
            :icon="item.imageUrl" 
            :text="item.title" 
         >
            <!-- 加载失败提示 -->
             <template #icon>
               <van-image :src="item.imageUrl" width="32" height="32">
                  <!-- <template v-slot:error>加载失败</template> -->
               </van-image>
             </template>
         </van-grid-item>
         <!-- <van-grid-item icon="photo-o" text="文字" />
         <van-grid-item icon="photo-o" text="文字" />
         <van-grid-item icon="photo-o" text="文字" /> -->
      </van-grid>
    </div>
 </div>
</template>

<script>
import { getCategorys, getSubCategorys } from '../../api/category'
export default {
 name: 'Category',
 data() {
   return {
      active: 0,
      categorys: [], // 所有主分类
      subCategorys: [] // 当前选中的子分类
   }
 },
 created(){
   this.getCategory()
 },
 methods: {
   // 获取一级菜单数据
   async getCategory(){
      const result = await getCategorys()
      console.log(result)
      this.categorys = result.list.slice(1)

      // 默认查询子分类数据渲染
      this.handleCateChange(0)
   },

   // 切换分类 监听事件
   async handleCateChange(index){
      console.log(index)
      // 判断当前切换的主分类下是否有其子分类
      if(this.categorys[index].children){
         this.subCategorys = this.categorys[index].children
         return
      }
      // 当前主分类下还有没有子分类数据，才查询数据

      // 获取当前主分类的 id
      const { id } = this.categorys[index]
      const result = await getSubCategorys(id)
      console.log(result)
      this.subCategorys = result.categories

      // 将查询到的子分类数据缓存到对应children中
      this.categorys[index].children = result.categories
   },
 }
}
</script>

<style lang="scss" scoped>
   .category {
      display: flex;
      // overflow-y: hidden;
      .right {
         flex: 1;
         padding: 6px;
      }
   }
</style>
